package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type IUserRepository interface {
	FindById(*gorm.DB, string) (*model.User, error)
	FindPage(*gorm.DB, *pagehelper.Params) ([]*model.User, error)
	Count(*gorm.DB, *pagehelper.Params) (int64, error)
}

type UserRepository struct {
}

func NewUserRepository() IUserRepository {
	return &UserRepository{}
}

func (r *UserRepository) FindById(db *gorm.DB, userId string) (user *model.User, err error) {
	return user, db.Model(&model.User{}).Where("user_id = ?", userId).First(&user).Error
}

func (r *UserRepository) FindPage(db *gorm.DB, params *pagehelper.Params) (list []*model.User, err error) {
	tx := queryWrapper.ReuseWherePair(db.Model(&model.User{}), params.WherePair)
	return list, tx.Scopes(pagehelper.Paginate(params.Current, params.Size)).Find(&list).Error
}

func (r *UserRepository) Count(db *gorm.DB, params *pagehelper.Params) (count int64, err error) {
	tx := queryWrapper.ReuseSelect(db.Model(&model.User{}), params.SelectFields)
	return count, queryWrapper.ReuseWherePair(tx, params.WherePair).Count(&count).Error
}
